package cn.yedong.pet.service.impl;

import cn.yedong.basic.exception.BusinessException;
import cn.yedong.basic.service.IBaiduAiAuditService;
import cn.yedong.basic.util.*;
import cn.yedong.order.domain.OrderPetAcquisition;
import cn.yedong.order.mapper.OrderPetAcquisitionMapper;
import cn.yedong.org.domain.Employee;
import cn.yedong.org.domain.Shop;
import cn.yedong.org.mapper.EmployeeMapper;
import cn.yedong.org.mapper.ShopMapper;
import cn.yedong.pet.domain.SearchMasterMsg;
import cn.yedong.pet.domain.SearchMasterMsgAuditLog;
import cn.yedong.pet.dto.MsgDto;
import cn.yedong.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.yedong.pet.mapper.SearchMasterMsgMapper;
import cn.yedong.pet.query.SearchMasterMsgQuery;
import cn.yedong.pet.service.ISearchMasterMsgService;
import cn.yedong.basic.service.impl.BaseServiceImpl;
import cn.yedong.user.domain.Logininfo;
import cn.yedong.user.domain.User;
import cn.yedong.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    /**
     *  发布寻主消息
     * @param msg
     * @param request
     * @return
     */
    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {
        //1.将寻主消息添加数据库【设置userId】
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        msg.setUserId(user.getId());
        searchMasterMsgMapper.add(msg);
        //2.百度AI智能审核
        Boolean textBoolean = baiduAiAuditService.textAudit(msg.getName() + msg.getTitle());
        Boolean msgBoolean = baiduAiAuditService.imageAudit(msg.getResources());
        //3.百度AI审核通过 - 添加审核日志 - 获取最近店铺
        if(textBoolean && msgBoolean){
            msg.setState(1);//寻主消息状态 - 待处理
            //添加审核日志 - 成功
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setState(1);//日志 - 成功
            searchMasterMsgAuditLog.setMsgId(msg.getId());
            searchMasterMsgAuditLog.setNote("审核成功！");
            searchMasterMsgAuditLogMapper.add(searchMasterMsgAuditLog);
            //获取附近店铺
            Point point = DistanceUtils.getPoint(msg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
            if(nearestShop != null){//50公里内有店铺
                msg.setShopId(nearestShop.getId());
//                SmsUtils.sendSms(nearestShop.getTel(),"您有新的订单，请前往"+msg.getAddress()+"收购宠物！");
                System.out.println("您有新的订单，请前往"+msg.getAddress()+"收购宠物！");
            }else {//50公里内没有店铺
                msg.setState(3);//放入寻主池
//                SmsUtils.sendSms(user.getPhone(),"您的附近没有店铺！");
                System.out.println("您的附近没有店铺！");
            }
            searchMasterMsgMapper.update(msg);
            //return前端
            return new AjaxResult();
        }
        //4.百度AI审核失败 - 添加审核日志
        SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
        searchMasterMsgAuditLog.setState(0);//日志 - 失败
        searchMasterMsgAuditLog.setMsgId(msg.getId());
        searchMasterMsgAuditLog.setNote("审核失败！");
        searchMasterMsgAuditLogMapper.add(searchMasterMsgAuditLog);
        //删除寻主消息
        searchMasterMsgMapper.del(msg.getId());
        //向用户发送提示短信
//        SmsUtils.sendSms(user.getPhone(),"您的寻主消息审核失败，请重新提交信息！");
        System.out.println("您的寻主消息审核失败，请重新提交信息！");
        //return前端
        return new AjaxResult(false,"您的寻主消息审核失败，请重新提交信息！");
    }

    /**
     * 【用户】查询自己的寻主消息 -
     * 在寻主消息query中增加userId字段，给其赋值userId，通过动态sql判断userId，动态显示分页数据
     * @param query
     * @param request
     * @return
     */
    @Override
    public QueryResult<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //用户查询自己的寻主消息，设置userId
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.pageQuery(query);
    }

    /**
     * 查询已经完成的寻主消息 -
     * 在寻主消息query中增加state字段，给其赋值 state=2，通过动态sql判断state，动态显示分页数据
     * 区分平台管理员 - 店铺管理员；动态显示分页数据
     * @param query
     * @param request
     * @return
     */
    @Override
    public QueryResult<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询已完成寻主消息
        query.setState(2);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.findByLoginfoId(logininfo.getId());
        if(employee.getShop_id() != null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.pageQuery(query);
    }

    /**
     * 在寻主消息query中增加state字段，给其赋值 state=3，通过动态sql判断state，动态显示分页数据
     * @param query
     * @param request
     * @return
     */
    @Override
    public QueryResult<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询放入寻主池寻主消息
        query.setState(3);
        return super.pageQuery(query);
    }

    /**
     * 查询寻主池的寻主消息 -
     * 在寻主消息query中增加state字段，给其赋值 state=1，通过动态sql判断state，动态显示分页数据
     * 区分平台管理员 - 店铺管理员；动态显示分页数据
     * @param query
     * @param request
     * @return
     */
    @Override
    public QueryResult<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //查询待处理寻主消息
        query.setState(1);
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.findByLoginfoId(logininfo.getId());
        if(employee.getShop_id() != null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.pageQuery(query);
    }

    /**
     * 拒单
     */
    @Override
    public void reject(Long id) {
        //拒单之后 - 放入寻主池 state=3，shopId置空
        searchMasterMsgMapper.reject(id);
    }

    /**
     * 接单
     * @param msgDto
     */
    @Override
    public void accept(MsgDto msgDto) {
        //1.判断当前订单是否正在处理:因为订单2天到期取消之后，可能会重新分配店铺，所以要判断state==0
        OrderPetAcquisition order = orderPetAcquisitionMapper.findByMsgId(msgDto.getMsgId());
        if(order != null && order.getState() == 0){//有订单；并且当前订单是待处理
            throw new BusinessException("订单正在处理，请勿重复接单！");
        }
        //2.生成收购订单 - 保存
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(msgDto.getMsgId());
        OrderPetAcquisition newOrder = createOrder(msg,msgDto);
        orderPetAcquisitionMapper.add(newOrder);
        //3.告诉收购人2天之内去收购宠物
//        Employee employee = employeeMapper.loadById(msgDto.getHandler());
//        SmsUtils.sendSms(employee.getPhone(),"您有新的订单，请在两天之内去"+msg.getAddress()+"收购宠物");
        System.out.println("您有新的订单，请在两天之内去"+msg.getAddress()+"收购宠物");
    }

    //根据寻主消息+接单信息  创建订单
    private OrderPetAcquisition createOrder(SearchMasterMsg msg, MsgDto msgDto) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        //使用工具类，根据寻主消息id生成订单号
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(msg.getId()));
        order.setDigest(msgDto.getNote());
        //设置两天过期
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        order.setPrice(msg.getPrice());
//        order.setPaytype();//不设置，接单时候才设置
//        order.setState();//默认值0
//        order.setPetId();//没有，宠物接回来才有
        order.setShopId(msg.getShopId());
        order.setUserId(msg.getUserId());
        order.setSearchMasterMsgId(msg.getId());
        order.setAddress(msg.getAddress());
        order.setEmpId(msgDto.getHandler());
        return order;
    }
}
